﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace CodeDOM2 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.exe|*.exe";
            DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK) {
                if (!string.IsNullOrEmpty(dialog.FileName)) {
                    Generate(dialog.FileName);
                } else {
                    MessageBox.Show("Filename invalid");
                }
            }
        }

        private static void Generate(string filename) {
            string code =
            @"
            using System;
            using System.Reflection;
            [assembly: AssemblyVersion(""0.9.0.0"")]
            namespace Hello {
                class Program {
                    static void Main(string[] args) {
                        Console.WriteLine(""Hello World"");
                        Console.ReadKey();
                    }
                }
            }";

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = true;
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.OutputAssembly = filename;
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
            if (results.Errors.Count == 0) {
                System.Windows.Forms.MessageBox.Show("Success");
            } else {
                string temp = null;
                for (int i = 0; i < results.Errors.Count; i++) {
                    temp += results.Errors[i].ErrorText + Environment.NewLine;
                }
                System.Windows.Forms.MessageBox.Show("Errors:" + temp);
            }
        }
    }
}
